package com.mentalhealthplatform.studentV3.service;

import com.mentalhealthplatform.appModels.Message;
import com.mentalhealthplatform.appModels.Reply;
import com.mentalhealthplatform.studentV3.repository.MessageRepositoryV3;
import com.mentalhealthplatform.studentV3.repository.ReplyRepositoryV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author Pear
 */
@Service
public class MessageServiceV3 {

    @Autowired
    private MessageRepositoryV3 messageRepositoryV3;

    @Autowired
    private ReplyRepositoryV3 replyRepositoryV3;

    // 保存新的留言
    public Message saveMessage(Message message) {
        return messageRepositoryV3.save(message);
    }

    // 根据学生ID获取留言
    public List<Message> getMessagesByStudentId(UUID studentId) {
        return messageRepositoryV3.findByStudentId(studentId);
    }

    // 回复留言
    public Optional<Message> getMessageById(Long messageId) {
        return messageRepositoryV3.findById(messageId);
    }

    public void addReplyToMessage(Long messageId, Reply reply) {
        Optional<Message> optionalMessage = getMessageById(messageId);
        if (optionalMessage.isPresent()) {
            Message message = optionalMessage.get();
            reply.setMessage(message);
            message.getReplies().add(reply);
            messageRepositoryV3.save(message);
        } else {
            throw new RuntimeException("留言不存在");
        }
    }

//    public List<Reply> getRepliesByMessageId(Long messageId) {
//        Optional<Message> optionalMessage = getMessageById(messageId);
//        if (optionalMessage.isPresent()) {
//            return optionalMessage.get().getReplies();
//        } else {
//            throw new RuntimeException("留言不存在");
//        }
//    }
    // 获取特定留言的所有回复
    public List<Reply> getRepliesByMessageId(Long messageId) {
        return replyRepositoryV3.findByMessageId(messageId);
    }
}



